<template>
  <a-layout class="bodyd" :style="{ height: lh + 'px' }">
    <a-layout-header>
      <span>物模型</span>
      <a-cascader
        :options="catalogs"
        :fieldNames="{
          label: 's_name',
          value: 'uid',
          children: 'children',
        }"
        @change="onChange"
        placeholder="请选择"
        :show-search="{ filter }"
        v-model="selValue"
        allowClear
        style="margin-left: 10px; width: 380px"
      />
      <a-space>
        <a-button @click="refresh">刷新</a-button>
        <a-button @click="find('modbus')">Modbus</a-button>
      </a-space>
    </a-layout-header>
    <div class="rowbody">
      <input
        type="file"
        multiple
        id="files"
        ref="refFile"
        style="display: none"
        v-on:change="fileLoad"
      />
      <a-layout v-if="currentModel">
        <a-layout-content style="width: 100%">
          <modbus-display
            :modbus="modbus"
            @save="onSave"
            @export="onExport"
            @rollback="onRollback"
            @importall="importAll"
            :mbody="mbody"
            ref="modbusDisplay"
          ></modbus-display>
        </a-layout-content>
      </a-layout>
    </div>
  </a-layout>
</template>
<script>
import { goAlongTree } from "@/utils/goAlongTree.js";
import { getByModelID, saveProtocol } from "@/services/protocol.js";
import ModbusDisplay from "@/components/modbus/ModbusDisplay";
import FileSaver from "file-saver";
export default {
  components: {
    ModbusDisplay,
  },
  computed: {
    lh() {
      return document.body.clientHeight - 148;
    },
    catalogs() {
      let catalogs = this.$store.state.tmodel.catalogModelTree;
      goAlongTree(catalogs, (c) => {
        if (c.ctype == "catalog" && (!c.children || c.children.length == 0)) {
          c.disabled = true;
        } else {
          c.disabled = false;
        }
      });
      return catalogs;
    },
  },
  data() {
    return {
      selValue: [],
      collapsed: false,
      protocols: [],
      currentModel: null,
      modbus: {},
      mbody: null,
    };
  },
  created() {
    this.refresh();
  },
  methods: {
    prepareData() {
      if (this.modbus && this.modbus) {
        let ms = JSON.stringify(this.modbus);
        let mj = JSON.parse(ms);
        if (mj && mj.service_cmds) {
          mj.service_cmds.forEach((c) => {
            delete c.obj;
            if (c.cmdType == "scan") {
              delete c.input_params;
            } else {
              delete c.scan;
            }
          });
        }
        return mj;
      }
      return null;
    },
    onSave() {
      let protocol = {
        model_id: this.currentModel.uid,
        protocol_path: "modbus",
        param: this.prepareData(),
      };
      saveProtocol(protocol);
    },
    onExport() {
      let protocol = {
        model_id: this.currentModel.uid,
        protocol_path: "modbus",
        param: this.prepareData(),
      };
      let sprotocol = JSON.stringify(protocol);
      const blob = new Blob([sprotocol], { type: "" });
      const filepath = this.currentModel.s_name + "_modbus" + ".json";
      FileSaver.saveAs(blob, filepath);
    },
    onRollback() {
      if (this.currentModel) {
        let self = this;

        getByModelID(this.currentModel.uid).then((res) => {
          if (res && res.data && res.data.result) {
            self.protocols = res.data.result;
            self.find("modbus");
          }
        });
      }
    },
    onChange(value, selectedOptions) {
      //console.log(value, selectedOptions);
      let index = selectedOptions.length - 1;
      this.modbus = null;
      if (index > 0) {
        let model = selectedOptions[index];
        this.currentModel = model;
        this.modbus = undefined;
        this.onRollback();
      }
    },
    find(name) {
      if (this.protocols) {
        let pro = this.protocols.find((p) => {
          return p.protocol_path == name;
        });
        if (!pro) {
          pro = {};
        }
        if (typeof pro.param == "string") {
          this.modbus = JSON.parse(pro.param);
        } else {
          this.modbus = pro.param;
        }
      }
      if (!this.modbus) {
        this.modbus = {};
      }
      if (!this.modbus.property_scans) {
        this.modbus.property_scans = [];
      }
      if (this.currentModel) {
        let mid = this.currentModel.uid;
        let self = this;
        this.$store.dispatch("tmodel/refreshTModelByID", mid).then(() => {
          let m = self.$store.state.tmodel.tmodelCache[mid];
          if (m) {
            if (m.obody) {
              self.mbody = m.obody;
            } else {
              if (typeof m.body == "string") {
                self.mbody = JOSN.parse(m.body);
              } else {
                self.mbody = m.body;
              }
            }
          }
        });
      }
    },
    refresh() {
      this.$store.dispatch("tmodel/refreshTModels");
    },
    filter(inputValue, path) {
      return path.some(
        (option) =>
          option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
      );
    },
    importAll() {
      this.$refs.refFile.dispatchEvent(new MouseEvent("click"));
    },
    fileLoad() {
      let self = this;
      this.$refs.refFile.files.forEach((selectedFile) => {
        var reader = new FileReader();
        reader.onload = function () {
          console.log("--------------", this.result);
          const data = JSON.parse(this.result);
          let protocol = {
            model_id: self.currentModel.uid,
            protocol_path: "modbus",
            param: data.param,
          };
          let index = self.protocols.findIndex((p) => {
            return p.protocol_path == "modbus";
          });
          if (index >= 0) {
            self.protocols[index] = protocol;
          } else {
            self.protocols.push(protocol);
          }
          self.find("modbus");
          self.$nextTick(() => {
            self.$refs.modbusDisplay.editStep(0);
          });

          //const blob = new Blob([data], {type: ''})
          //FileSaver.saveAs(blob, filepath)
        };
        //const record = this.currentRecord
        console.log("XXXXXXXXXXXXXXXXXXXX", selectedFile);
        reader.readAsText(selectedFile);
        const _this = this;
      });
      this.$refs.refFile.value = "";
      //const selectedFile = this.$refs.refFile.files[0];
    },
  },
};
</script>
<style lang="less" scoped>
.bodyd {
  display: flex;
}
.ant-layout-header {
  background: @body-background;
  flex-grow: 0;
  color: @text-color;
}
.rowbody {
  display: flex;
  flex-direction: column;

  height: 100vh;
}
.sider {
  background: @body-background;
}
.rowheight {
  background: @body-background;
  border: 1px dotted red;
  flex: 1 auto;
  height: auto;
}
.ant-layout-content {
  flex: 0;
  flex: 1;
}
</style>

